package com.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.changgou.goods.pojo.Brand;
import com.changgou.search.pojo.SkuInfo;
import com.search.dao.ESManagerMapper;
import com.search.service.SearchService;
import org.apache.commons.lang.StringUtils;
import org.apache.tomcat.util.json.JSONParserConstants;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.MatchQueryBuilder;
import org.elasticsearch.index.query.Operator;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.StringTerms;
import org.elasticsearch.search.aggregations.bucket.terms.StringTermsAggregator;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.SearchResultMapper;
import org.springframework.data.elasticsearch.core.aggregation.AggregatedPage;
import org.springframework.data.elasticsearch.core.aggregation.impl.AggregatedPageImpl;
import org.springframework.data.elasticsearch.core.facet.FacetResult;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;

import javax.validation.constraints.Null;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

@Service
public class SearchServiceImpl implements SearchService {
    @Autowired
    private ElasticsearchTemplate elasticsearchTemplate;
    @Autowired
    private ESManagerMapper esManagerMapper;
    public final static Integer PAGE_SIZE = 20;

    @Override
    public Map search(Map<String, String> parammap) {
        Map<String, Object> resulMap = new HashMap<>();
        if (parammap != null) {
            BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
            if (parammap.get("keywords") != null) {
                boolQueryBuilder.must(QueryBuilders.matchQuery("name", parammap.get("keywords")).operator(Operator.AND));
            }
            NativeSearchQueryBuilder nativeSearchQueryBuilder = new NativeSearchQueryBuilder();
            nativeSearchQueryBuilder.withQuery(boolQueryBuilder);
            AggregatedPage<SkuInfo> resultinfo = elasticsearchTemplate.queryForPage(nativeSearchQueryBuilder.build(), SkuInfo.class, new SearchResultMapper() {
                @Override
                public <T> AggregatedPage<T> mapResults(SearchResponse searchResponse, Class<T> aClass, Pageable pageable) {

                    List<T> list = new ArrayList<>();
                    SearchHits hits = searchResponse.getHits();
                    if (hits != null) {
                        for (SearchHit hit : hits) {
                            SkuInfo skuInfo = JSON.parseObject(hit.getSourceAsString(), SkuInfo.class);
                            list.add((T) skuInfo);

                        }
                    }
                    return new AggregatedPageImpl<T>(list, pageable, hits.getTotalHits(), searchResponse.getAggregations());

                }
            });
            resulMap.put("total", resultinfo.getTotalElements());
            resulMap.put("totalpages", resultinfo.getTotalPages());
            resulMap.put("rows", resultinfo.getContent());

            return resulMap;
        }
        return null;
    }

    @Override
    public Map searchcondition(Map<String, String> smap) {
        if (smap != null) {
            BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
            if (smap.get("keywords") != null) {
                boolQueryBuilder.must(QueryBuilders.matchQuery("name", smap.get("keywords")).operator(Operator.AND));
            }
            if (smap.get("brand") != null) {
                boolQueryBuilder.filter(QueryBuilders.termQuery("brandName", smap.get("brand")));
            }
            if (smap.get("categoryName") != null) {
                boolQueryBuilder.filter(QueryBuilders.termQuery("categoryName", smap.get("categoryName")));
            }
            for (String s : smap.keySet()) {
                if (s.startsWith("spec_")){
                    String value = smap.get(s).replace("%2B", "+");
                    boolQueryBuilder.filter(QueryBuilders.matchQuery("specMap."+s.substring(5)+".keyword",value));
                }
            }
            if (smap.get("price")!=null){
              String[] p= smap.get("price").split("-");
              if (p.length==2){
              boolQueryBuilder.must(QueryBuilders.rangeQuery("price").lte(p[1]));
              boolQueryBuilder.must(QueryBuilders.rangeQuery("price").gte(p[0]));
            }}



            NativeSearchQueryBuilder nativeSearchQueryBuilder = new NativeSearchQueryBuilder();
            nativeSearchQueryBuilder.withQuery(boolQueryBuilder);
            //关键字高亮查询
            HighlightBuilder.Field field=new HighlightBuilder.Field("name")
                    .preTags("<span style='color:red'>")
                    .postTags("</span>");
            nativeSearchQueryBuilder.withHighlightFields(field);
            //品牌聚合分组查询
            nativeSearchQueryBuilder.addAggregation(AggregationBuilders.terms("skuBrand")
                    .field("brandName"));
            //规格聚合分组查询
            nativeSearchQueryBuilder.addAggregation(AggregationBuilders.terms("skuSpec")
                    .field("spec.keyword"));
           //排序
            if (!StringUtils.isEmpty(smap.get("sortField"))){
                if ("ASC".equals(smap.get("sortRule"))){
                    nativeSearchQueryBuilder.withSort(SortBuilders.fieldSort(smap.get("sortField")).order(SortOrder.ASC));
                }
                else {
                    nativeSearchQueryBuilder.withSort(SortBuilders.fieldSort(smap.get("sortField")).order(SortOrder.DESC));
                }
            }
            //分页
            String pageNum = smap.get("pageNum");
            if (pageNum==null||Integer.parseInt(pageNum)<=0){
                pageNum="1";
            }
            nativeSearchQueryBuilder.withPageable(PageRequest.of(Integer.parseInt(pageNum)-1,PAGE_SIZE));

            AggregatedPage<SkuInfo> aggregatedPage = elasticsearchTemplate.queryForPage(nativeSearchQueryBuilder.build(), SkuInfo.class, new SearchResultMapper() {
                @Override
                public <T> AggregatedPage<T> mapResults(SearchResponse searchResponse, Class<T> aClass, Pageable pageable) {
                    List<T> skuInfoList = new ArrayList<>();
                    SearchHits hits = searchResponse.getHits();
                    if (hits != null) {
                        for (SearchHit hit : hits) {
                            SkuInfo skuInfo = JSON.parseObject(hit.getSourceAsString(), SkuInfo.class);
                         Map<String,HighlightField> highlightFieldMap
                            =hit.getHighlightFields();
                         if (highlightFieldMap.size()>0&&highlightFieldMap!=null){
                             skuInfo.setName(highlightFieldMap.get("name").getFragments()[0].toString());
                         }
                            skuInfoList.add((T) skuInfo);
                        }
                    }
                    return new AggregatedPageImpl<T>(skuInfoList, pageable, hits.getTotalHits(), searchResponse.getAggregations());
                }
            });
            Map resultmap = new HashMap();
            resultmap.put("total", aggregatedPage.getTotalElements());
            resultmap.put("totalpage", aggregatedPage.getTotalPages());
            resultmap.put("rows", aggregatedPage.getContent());
            resultmap.put("pageNum",pageNum);
            resultmap.put("pageSize",PAGE_SIZE.toString());


            //聚合品牌结果
            StringTerms brandTerms =(StringTerms) aggregatedPage.getAggregation("skuBrand");
            List<String> brandList=brandTerms.getBuckets().stream().map(bucket -> bucket.getKeyAsString()).collect(Collectors.toList());
            resultmap.put("brandList",brandList);
            //聚合规格信息
            StringTerms skuSpecterms =(StringTerms) aggregatedPage.getAggregation("skuSpec");
            List<String> specList=skuSpecterms.getBuckets().stream().map(bucket -> bucket.getKeyAsString()).collect(Collectors.toList());

            //去重
            resultmap.put("specList",dw(specList));
            return resultmap;


        }
        return null;
    }
    public Map<String,Set<String>> dw(List<String> specList){
        Map<String,Set<String>> specMap=new HashMap<>();
        for (String s : specList) {
            Map<String,String> map = JSON.parseObject(s, Map.class);
            Set<Map.Entry<String, String>> entries = map.entrySet();
            for (Map.Entry<String, String> entry : entries) {
                String key = entry.getKey();
                String value = entry.getValue();
                Set<String> specValues=specMap.get(key);
                if (specValues==null){
                    specValues=new HashSet<>();
                }
                specValues.add(value);
                specMap.put(key,specValues);
            }
        }
        return specMap;
    }

}
